<?php

/**
* alltosun.com 退货控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2014-8-8 下午6:47:43 $
* $Id$
*/

class Action
{
    private $per_page = 10;

     /**
     * 显示退货列表
     */
    public function index()
    {
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $refund_status = Request::getParam('refund_status', 0);
        $is_advenced   = Request::Get('is_advenced', 1);
        $search_filter = Request::getParam('search_filter', array());

        // 拼装搜索条件
        $is_empty = 0;
        $filter = array();
        $user_filter = array();
        $goods_filter = array();
        if (isset($search_filter['refund_id']) && $search_filter['refund_id']) {
            $refund_id = order_helper::order_id_decode($search_filter['refund_id']);
            if(is_numeric($refund_id)) {
                $filter['id'] = $refund_id;
            }
        }
        if (isset($search_filter['refund_status']) && $search_filter['refund_status']) {
            $filter['refund_status'] = $search_filter['refund_status'];
        }
        if (isset($search_filter['order_id']) && $search_filter['order_id']) {
            $order_id = order_helper::order_id_decode($search_filter['order_id']);
            if(is_numeric($order_id)) {
                $filter['order_id'] = $order_id;
            }
        }
        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_filter['`user_name` LIKE'] = '%'.$search_filter['user_name'].'%';
            $user_filter['status'] = 1;
            $user_ids = _model('user')->getFields('id', $user_filter);
            $filter['user_id'] = $user_ids;
        }
        if (isset($search_filter['goods_title']) && $search_filter['goods_title']) {
            //通过快照查询order_ids
            $goods_filter['`goods_title` LIKE '] = '%'.$search_filter['goods_title'].'%';
            $goods_filter['status'] = 1;
            $goods_snapshot_ids = _model('sku_snapshot')->getFields('id', $goods_filter);
            if ($goods_snapshot_ids) {
                $refund_ids = _model('refund_relation')->getFields('refund_id', array('sku_snapshot_id'=>$goods_snapshot_ids));
                $refund_ids = array_unique($refund_ids);
                $filter['id'] = $refund_ids;
            } else {
                $filter['id'] = 0;
            }
        }
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'].' 00:00:00';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'].' 23:59:59';
        }
        if (isset($refund_status) && $refund_status) {
            $filter['refund_status'] = $refund_status;
        }
        $filter['type']   = 1;
        //$filter['status'] = $status;

        $refund_list = array();
        if (!$is_empty) {
            $refund_count = _model('refund')->getTotal($filter);
            if ($refund_count) {
                $pager = new Pager($this->per_page);
                if ($pager->generate($refund_count)) {
                    Response::assign('pager', $pager);
                }

                $refund_list = _model('refund')->getList($filter, ' ORDER BY `add_time` DESC '.$pager->getLimit($page));

                Response::assign('count', $refund_count);
            }
        }

        Response::assign('refund_list', $refund_list);
        Response::assign('refund_status', $refund_status);
        Response::assign('status', $status);
        Response::assign('search_filter', $search_filter);
        Response::assign('is_advenced', $is_advenced);
        Response::display('admin/refund_list.html');
    }

    /**
     * 取消退款
     * @return [type] [description]
     */
    public function cancel_refund()
    {
        $id = Request::getParam('id', 0);
        if (!$id) {
            return '请选择需要操作的退款单';
        }

        $refund_info = _uri('refund', $id);
        $order_info  = _uri('order', $refund_info['order_id']);

        if ($order_info['progress'] == 0 && in_array($refund_info['refund_status'], array(5, 15)) && !$refund_info['user_express'] && !$refund_info['refund_express']) {
            _model('refund')->update(array('id'=>$refund_info['id']), array('refund_status'=>25, 'status'=>0));
            _model('order')->update(array('id'=>$order_info['id']), array('progress'=>10));
            return 'ok';
        }

        return '当前退款单不能取消';
    }

    /**
     * 强制取消退款
     */
    public function cancel_refund_root()
    {
        $id = Request::getParam('id', 0);
        $key = Request::getParam('key', '');
        if (!$id) {
            return '请选择需要操作的退款单';
        }
        if (!$key) {
            return '没有权限操作订单取消';
        }
        if ($key != alltosunXXnbd) {
            return '01';
        }

        $refund_info = _uri('refund', $id);
        if (!$refund_info) {
            return '当前退款单不存在';
        }
        $order_info  = _uri('order', $refund_info['order_id']);
        if (!$order_info) {
            return '';
        }

        if ($order_info['progress'] == 0 && in_array($refund_info['refund_status'], array(23)) && !$refund_info['user_express'] && !$refund_info['refund_express']) {
            _model('refund')->update(array('id'=>$refund_info['id']), array('refund_status'=>25, 'status'=>0));
            _model('order')->update(array('id'=>$order_info['id']), array('progress'=>10));
            return 'ok';
        }

        return '当前退款单不能取消';
    }

    /**
     * ajax请求获取批量退款列表
     */
    public function ajax_process_list()
    {
        $ids = Request::getParam('ids', 0);

        if (!$ids) {
            return 'error';
        }

        $ids = explode(',', $ids);
        $filter = array(
            'id' => $ids,
            'type' => 1,
            //'refund_status' => 20
        );

        $process_list = _model('refund')->getList($filter);

        Response::assign('process_list', $process_list);
        Response::display('admin/process_refund.html');
    }

    /**
     * ajax处理退款
     */
    public function ajax_request_refund()
    {
        $id = Request::getParam('id', 0);

        if (!$id) {
            return '请选择需要退款的订单';
        }

        $refund_info = _uri('refund', $id);
        if ($refund_info['type'] == 1) {
            _model('refund')->update(array('id'=>$id), array('is_view'=>0));

            $order_info = _uri('order', $refund_info['order_id']);
            $pay_type = $order_info['pay_type'];
            $url = AnUrl(openapi_config::$pay_type[$pay_type]['refund']);
            $result = an_curl($url, array('refund_id'=>$id));
            
            // if($pay_type != 2) {
            //     _model('refund')->update(array('id'=>$id), array('refund_status'=>15, 'refund_time'=>date('Y-m-d H:i:s')));
            // }
            return $result;
        }

        return '退款失败';
    }

    /**
     * ajax请求退货详细信息
     */
    public function ajax_refund_info()
    {
        $id = Request::getParam('id', 0);

        if (!$id) {
            return 'error';
        }

        $refund_info = service_helper::get_refund_info($id, 0);

        Response::assign('refund_info', $refund_info);
        Response::display('admin/details.html');
    }

    /**
     * 修改信息
     */
    public function edit_refund_relation()
    {
        $relation_id = Request::getParam('relation_id', 0);
        $refund_num  = Request::getParam('refund_num', 0);
        if (!$relation_id) {
            return '请选择需要修改的退款订单';
        }

        $refund_relation_info = _uri('refund_relation', $relation_id);
        $order_relation_info  = _uri('order_relation', $refund_relation_info['order_relation_id']);
        $refund_info = _uri('refund', $refund_relation_info['refund_id']);
        if ($refund_info['refund_status'] != 1) {
            return '当前退款订单已不在可修改状态';
        }
        if ($refund_num > $order_relation_info['goods_num']) {
            $refund_num = $order_relation_info['goods_num'];
        }

        _model('refund_relation')->update(array('id'=>$relation_id), array('refund_num'=>$refund_num));

        $refund_price = service_helper::update_refund_total($refund_relation_info['refund_id']);
        _model('refund')->update(array('id'=>$refund_relation_info['refund_id']), array('refund_price'=>$refund_price));

        return array(
            'info' => 'ok',
            'count' => number_format($refund_price, 2),
            'id'    => $refund_relation_info['refund_id']
        );
    }

    /**
     * 删除信息
     */
    public function delete_refund_relation()
    {
        $relation_id = Request::getParam('relation_id', 0);
        $status      = Request::getParam('status', 0);
        if (!$relation_id) {
            return '请选择需要删除的退款订单';
        }

        $refund_relation_info = _uri('refund_relation', $relation_id);
        $refund_info = _uri('refund', $refund_relation_info['refund_id']);
        if ($refund_info['refund_status'] != 1) {
            return '当前退款订单已不在可修改状态';
        }

        _model('refund_relation')->update(array('id'=>$relation_id), array('status'=>$status));

        $refund_price = service_helper::update_refund_total($refund_relation_info['refund_id']);
        _model('refund')->update(array('id'=>$refund_relation_info['refund_id']), array('refund_price'=>$refund_price));

        return array(
            'info' => 'ok',
            'count' => number_format($refund_price, 2),
            'id'    => $refund_relation_info['refund_id']
        );
    }

    /**
     * edit_real_price
     */
    public function edit_real_price()
    {
        $refund_id  = Request::getParam('refund_id', 0);
        $refund_price = Request::getParam('refund_price', '');

        if (!$refund_id) {
            return '请选择需要修改的退款单';
        }
        if ($refund_price < 0) {
            return '价格不能为负数';
        }

        _model('refund')->update(array('id'=>$refund_id), array('real_price'=>$refund_price, 'is_modify_price'=>1));

        return array(
            'info'=>'ok',
            'price' => number_format($refund_price, 2)
        );
    }

    /**
     * 更改退货单状态
     */
    public function change_refund_status()
    {
        $id = Request::Get('id', 0);
        $refund_status = Request::Get('refund_status', 0);
        $note = Request::Get('note', '');

        if ($refund_status ==30 && !$note) {
            return '驳回理由不能为空';
        }
        if (!$refund_status) {
            return '要修改的退货状态不能为空';
        }
        $info = _uri('refund', array('id'=>$id, 'status'=>1));
        if (!$info) {
            return '该退货单不存在或被删除';
        }
        if ($info['refund_status'] == $refund_status) {
            return '要修改的状态不能和原状态一致';
        }

        $filter['refund_status'] = $refund_status;
        if ($refund_status == 5) {
            $filter['agree_time'] = date('Y-m-d H:i:s');
        }

        if ($note) {
            $filter['refund_reason'] = AnFilter::filter_string($note);
        }

        $filter['is_view'] = 0;
        $status = _model('refund')->update(array('id'=>$id), $filter);

        if ($status) {
            $reufnd_info = _uri('refund', $id);
            $email = _uri('user', $reufnd_info['user_id'], 'email');
            $goods_title = service_helper::get_goods_title($id);
            if ($refund_status == 30) {
                order_helper::sendExpressMessage('return_goods_error', array($goods_title), $reufnd_info['mobile'], $email);
            } else if ($refund_status == 5) {
                order_helper::sendExpressMessage('return_goods_success', array($goods_title), $reufnd_info['mobile'], $email);
            }
        }

        Response::redirect('refund/admin');
    }

    /**
     * 删除
     * @return array
     */
    public function delete()
    {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k=>$v) {
            if (!$v) {
                continue;
            }

            $order_info = _uri('order', (int)$v);
            if (!$order_info) {
                continue;
            }

            if ($order_info['order_status'] != 5) {
                continue;
            }

            if (1 == $order_info['status']) {
                _model('order')->update($v, array('status'=>0));
            } else {
                _model('order')->delete($v);
            }
        }

        return 'ok';
    }

    /**
     * 更改状态
     * @return array
     */
    public function change_status(){
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);

        if (!$id) {
            return '请选择要更改的内容';
        }

        $order_info = _uri('order', $id);
        if ($status == $order_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('order')->update($id, array('status'=>1));
        }

        return 'ok';
    }

    /**
     * 退款前填写信息
     */
    public function get_refund_before_info()
    {
        $id = Request::getParam('id', 0);

        if (!$id) {
            return 'error';
        }

        $refund_info = service_helper::get_refund_info($id, 0);

        $order_info  = _uri('order', $refund_info['order_id']);
        if ($order_info) {
            Response::assign('order_info', $order_info);
        }

        Response::assign('refund_info', $refund_info);

        Response::display('admin/refund_price.html');
    }

    /**
     * 更新 退款类型
     */
    public function update_refund_type()
    {
        $id = Request::getParam('id', 0);
        $refund_type = Request::getParam('refund_type', 0);
        $sn_code      = Request::getParam('sn_code', '');
        $invoice_no   = trim(Request::getParam('invoice_no', ''));
        $invoice_code = trim(Request::getParam('invoice_code', ''));
        if (!$refund_type || 0 == $refund_type) {
            return '请选择退款类型';
        }
        if (!$id) {
            return '请选择需要退款的订单';
        }
        $refund_info = _uri('refund', $id);

        if($sn_code) {
            $sn_arr = explode('#', $sn_code);
            foreach ($sn_arr as $k=>$v) {
                $relation_arr = explode(':', $v);
                _model('order_relation')->update($relation_arr[0], array('sn_code'=>$relation_arr[1]));
            }
        }
        if ($invoice_no && $invoice_code) {
            $order_id = $refund_info['order_id'];
            _model('order')->update($order_id, array('invoice_no'=>$invoice_no, 'invoice_code'=>$invoice_code));
        }

        $info = array(
                    'refund_type'=>$refund_type,
                    'op_id'=>user_helper::get_user_id()
                );
        if ($refund_info['refund_status'] == 1) {
            $info['refund_status'] = 5;
            $info['agree_time'] = date('Y-m-d H:i:s');
        }

        _model('refund')->update($id, $info);

        $order_info = _uri('order', $refund_info['order_id']);

        _widget('erp_lenovo.erp_lenovo_order')->AddREOrder($refund_info['id']);

        return 'ok';
    }

    public function download_list()
    {
        //$status        = Request::Get('status', 1);
        $refund_status = Request::getParam('refund_status', 0);
        $is_advenced   = Request::Get('is_advenced', 1);
        $search_filter = Request::getParam('search_filter', array());

        // 拼装搜索条件
        $is_empty = 0;
        $filter = array();
        $user_filter = array();
        $goods_filter = array();
        if (isset($search_filter['refund_id']) && $search_filter['refund_id']) {
            $refund_id = order_helper::order_id_decode($search_filter['refund_id']);
            if(is_numeric($refund_id)) {
                $filter['id'] = $refund_id;
            }
        }
        if (isset($search_filter['refund_status']) && $search_filter['refund_status']) {
            $filter['refund_status'] = $search_filter['refund_status'];
        }
        if (isset($search_filter['order_id']) && $search_filter['order_id']) {
            $order_id = order_helper::order_id_decode($search_filter['order_id']);
            if(is_numeric($order_id)) {
                $filter['order_id'] = $order_id;
            }
        }
        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_filter['`user_name` LIKE'] = '%'.$search_filter['user_name'].'%';
            $user_filter['status'] = 1;
            $user_ids = _model('user')->getFields('id', $user_filter);
            $filter['user_id'] = $user_ids;
        }
        if (isset($search_filter['goods_title']) && $search_filter['goods_title']) {
            //通过快照查询order_ids
            $goods_filter['`goods_title` LIKE '] = '%'.$search_filter['goods_title'].'%';
            $goods_filter['status'] = 1;
            $goods_snapshot_ids = _model('sku_snapshot')->getFields('id', $goods_filter);
            if ($goods_snapshot_ids) {
                $refund_ids = _model('refund_relation')->getFields('refund_id', array('sku_snapshot_id'=>$goods_snapshot_ids));
                $refund_ids = array_unique($refund_ids);
                $filter['id'] = $refund_ids;
            } else {
                $filter['id'] = 0;
            }
        }
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['add_time >='] = $search_filter['start_date'].' 00:00:00';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['add_time <='] = $search_filter['end_date'].' 23:59:59';
        }
        if (isset($refund_status) && $refund_status) {
            $filter['refund_status'] = $refund_status;
        }
        $filter['type']   = 1;
        //$filter['status'] = $status;

        $refund_list = array();
        if (!$is_empty) {
            $refund_count = _model('refund')->getTotal($filter);
            if ($refund_count) {
                $refund_list = _model('refund')->getList($filter, ' ORDER BY `add_time` DESC ');

            }
        }

        $this->export_excel($refund_list);
    }

    /**
     * 用户订单表
     */
    public function export_excel($list = array())
    {
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F');
        // 第一排的标题
        $col_title_arr = array('退货单号', '退货状态', '订单信息', '订单状态', '退款总金额', '商家备注');
        $col_content_arr = array('refund_info', 'refund_status', 'order_info', 'progress', 'real_price', 'note');
        // 设置文档属性
        foreach ($col_arr as $k => $v) {
            //设置4个列的宽度
            if (in_array($v, array('A', 'C'))) {
                $objActSheet->getColumnDimension($v)->setWidth(60);
            } else {
                $objActSheet->getColumnDimension($v)->setWidth(20);
            }
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v."1", $col_title_arr[$k]);
            //格式化数字为字符串，避免导致数字默认右对齐单元格
            $objActSheet->getStyle($v)->getNumberFormat()->setFormatCode("@");
            //设置自动换行
            $objActSheet->getStyle($v)->getAlignment()->setWrapText(true);
        }

        // 填充单元格
        $refund_status_list = refund_config::$refund_status_list;
        $key = 2;
        foreach ($list as $k=>$v) {
            $order_info = _uri('order', $v['order_id']);
            if (!$order_info) {
                continue;
            }
            // 先将合并的信息填入excl
            foreach ($col_arr as $k2=>$v2) {
                $place = $v2.$key;
                $col_content = $col_content_arr[$k2];

                $value = '';
                if ($col_content == 'refund_info') {
                    $value = 'NBD退款编号：'.order_helper::order_id_encode($v['id'], 2)."\n";
                    $value .= 'ERP退款编号：'.$v['erp_refund_id']."\n";
                    $value .= '支付宝退款交易号：'.$v['transaction_id'];
                } elseif ($col_content == 'refund_status') {
                    $value = $refund_status_list[$v['refund_status']];
                } elseif ($col_content == 'order_info') {
                    $value = 'NBD订单编号：'.order_helper::order_id_encode($order_info['id'])."\n";
                    $value .= 'ERP订单编号：'.$order_info['erp_order_id']."\n";
                    $value .= '支付宝交易号：'.$order_info['transaction_id']."\n";
                    if ($order_info['origin'] == 'm') {
                        $value .= '订单来源：手机端'."\n";
                    } else {
                        $value .= '订单来源：PC端'."\n";
                    }
                    $value .= '下单用户：'.user_helper::get_nick_name($v['user_id']);
                } elseif ($col_content == 'progress') {
                    $value = order_config::$dealer_progress[$order_info['progress']];
                } elseif ($col_content == 'real_price') {
                    $value = ' '.$v['real_price'];
                } elseif ($col_content == 'note') {
                    $value = $v['note'];
                }

                $objActSheet->setCellValue($place, $value);
            }
            $key++;
            usleep(1000);
        }

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = date('Y-m-d')."NBD退款信息.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/',$_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=".$title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 手动完成退款
     */
    public function refund_complete_by_user()
    {
        $refund_id = Request::Post('id', 0);
        if(!$refund_id) {
            return "参数错误";
        }
        $refund_info = _model('refund')->read($refund_id);
        if(!$refund_info) {
            return "没有此退款信息";
        }
        if($refund_info['refund_status'] != 23) {
            return "此退款不处于退款失败状态，不能手动更改";
        }

        $order_info = _uri('order', $refund_info['order_id']);

        $info = array(
                        'refund_status'  => 20,
                        'refund_pay_status' => 2,
                        'refunded_time'     => date('Y-m-d H:i:s')
        );
        _model('refund')->update(array('id'=>$refund_info['id'], 'refund_status'=>23), $info);
        $info = _widget('erp_lenovo.erp_lenovo_order')->AddREOrder($refund_info['id']);

        // 发送退款完成短信
        order_helper::sendExpressMessage('refund_success', array(order_helper::order_id_encode($order_info['id'])), $order_info['mobile']);
        log_helper::create_refund_log('alipay', array(
                        'transaction_id' => $order_info['transaction_id'],
                        'order_id'       => $order_info['id'],
                        'refund_id'      => $refund_info['id'],
                        'transaction_refund_id' => '',
                        'refund_fee'     => $refund_info['real_price'],
                        'refund_status'  => 'success',
                        'ret_msg'        => '手工确认退款成功'
        ));

        return 'ok';
    }
}
?>